package search.concurrent;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.LinkedBlockingQueue;

import worker.StringSearch;
import downloader.URLDownloader;

public class StringSearchEngine {

	ExecutorService threadpool = null;
	BlockingQueue<String> urlQueue = null;
	List<Future<String>> output = null;
	int threadSize = 0;
	
	public StringSearchEngine(int threadSize) {
		threadpool = Executors.newFixedThreadPool(threadSize);
		urlQueue = new LinkedBlockingQueue<String>();
		output = new ArrayList<Future<String>>();
		this.threadSize = threadSize;
	}
	
	public void start(){
		List<String> urls =  URLDownloader.getURL("file:///c:/temp/input/url.txt");
		Set<String> searchPattern = new HashSet<String>(URLDownloader.getURL("file:///c:/temp/input/string.txt"));
		urlQueue.addAll(urls);
		for (int i = 0; i < threadSize; i++) {
			output.add(threadpool.submit(new StringSearch(urlQueue,searchPattern )));
		}
		
		for(Future<String> future : output){
			try {
				System.out.println(future.get());				
			} catch (InterruptedException | ExecutionException e) {
				e.printStackTrace();
			}
		}		
		shutdown();
	}
	private void shutdown(){
		this.threadpool.shutdown();
	}
	
	public static void main(String[] args) {
		StringSearchEngine engine = new StringSearchEngine(10);
		engine.start();
	}
}
